// pages/index/indexDetail.js
import api from "../../utils/apis.js";
import message from "../../utils/message.js";
import util from "../../utils/util.js";

Page({
  
  data: {
    pageSize: 20,
    pageNum: 0,
    dataArray: [],
    originalArr: [],
    bottomTitle: '点击加载更多',

    isWithdrawShow: false,
    withdrawNum: null,
    isWithdrawConfirm: false,
    walletInfo: {}
  },

  onLoad: function(options) {
    let self = this;

    self.loadWalletData();
  },

  onPullDownRefresh: function() {
    let self = this;
    
    self.setData({
      pageNum: 0
    })

    self.loadWalletData();
  },

  onReachBottom: function() {
    if (this.data.bottomTitle === '无更多数据') {
      return
    }

    this.loadMoreAction();
  },

  loadWalletData() {
    let self = this;

    let token = wx.getStorageSync("authorization");

    wx.showLoading({
      title: "加载中"
    });

    wx.request({
      url: api.walletInfoApi,
      method: "GET",
      header: {
        Authorization: "Bearer " + token
      },
      success(res) {
        wx.hideLoading();
        self.loadWalletDetailData(self.data.pageNum);

        if (res.statusCode == "200") {
          let data = res.data;

          self.setData({
            walletInfo: data
          });
        } else {
          util.errHandler(res)
        }
      }
    });
  },

  loadWalletDetailData(pageNum) {
    let self = this;

    let token = wx.getStorageSync("authorization");

    wx.showLoading({
      title: "加载中"
    });

    wx.request({
      url: api.walletDetailApi + "?" + "page=" + pageNum + "&size=" + "20",
      method: "GET",
      header: {
        Authorization: "Bearer " + token
      },
      success(res) {
        wx.hideLoading();
        wx.stopPullDownRefresh();
        if (res.statusCode == "200") {
          let data = res.data;

          if (data.length == 0) {
            self.setData({
              bottomTitle: '无更多数据'
            });
            return
          }

          if (pageNum == 0) {
            self.setData({
              originalArr: []
            });
          }

          data.forEach(element => {
            self.data.originalArr.push(element);
          });

          self.setData({
            dataArray: self.filterData(self.data.originalArr)
          });
        } else {
          util.errHandler(res)
        }
      }
    });
  },

  filterData(originalArr) {
    let temp = [];
    originalArr.forEach(element => {
      temp.push(element.date.substring(0, 7));
    });

    let uniqArr = util.uniq(temp);

    let outerArr = [];
    uniqArr.forEach(element => {
      let obj = {};
      obj.sectionTitle = element;
      obj.sectionData = [];
      outerArr.push(obj);
    });

    outerArr.forEach(element => {
      originalArr.forEach(innerEle => {
        if (innerEle.date.substring(0, 7) == element.sectionTitle) {
          let obj = {};
          if (innerEle.tradeType == 1) {
            obj.num = "-" + innerEle.displayProfitAmount;
          } else {
            obj.num = "+" + innerEle.displayProfitAmount;
          }

          obj.time = innerEle.date;

          if (innerEle.tradeType == 1) {
            obj.title = "提现";
          } else if (innerEle.tradeType == 2) {
            obj.title = "收益";
          } else if (innerEle.tradeType == 3) {
            obj.title = "节点收益";
          } else if (innerEle.tradeType == 4) {
            obj.title = "算力收益";
          } else if (innerEle.tradeType == 5) {
            obj.title = "共建收益";
          }

          element.sectionData.push(obj);
        }
      });
    });

    outerArr.forEach(element => {
      element.sectionTitle.replace('-', '年') + '月'
    })

    return outerArr;
  },

  loadMoreAction: function() {
    let self = this;

    if (self.data.bottomTitle === '无更多数据') {
      return
    }

    let temp = self.data.pageNum;
    temp += 1;
    self.setData({
      pageNum: temp
    });

    self.loadWalletDetailData(self.data.pageNum);
  },

  gotoWithdraw: function () {
    this.getbaseInfo()
  },

  withdrawInput(e) {
    this.setData({
      withdrawNum: e.detail.value
    });
  },

  cancelAction() {
    this.setData({
      isWithdrawShow: false,
      isWithdrawConfirm: false
    });
  },

  allCashAction() {
    let total = this.data.walletInfo.balanceAmount

    this.setData({
      withdrawNum: total
    })
  },

  ensureAction() {
    let self = this
    if (self.data.withdrawNum == 0 || self.data.withdrawNum == null) {
      message.showWarning('提现金额有误')
      return
    }

    self.setData({
      isWithdrawShow: false,
      isWithdrawConfirm: true
    });
  },

  getbaseInfo() {
    let self = this;
    let token = wx.getStorageSync("authorization");

    wx.showLoading({
      title: "加载中"
    });
    wx.request({
      url: api.getBaseInfoApi,
      method: "GET",
      header: {
        Authorization: "Bearer " + token
      },
      success(res) {
        wx.hideLoading();
        if (res.statusCode == 200) {

          if (res.data.mobile && res.data.mobile != 'null') {
          } else {
            message.showWarning('请绑定手机号码')
            return
          }

          if (res.data.cashWallet && res.data.cashWallet != 'null') {
          } else {
            message.showWarning('请绑定钱包地址')
            return
          }

          wx.showToast({
            title: '由于当前处于开发网络，所获得的均为模拟收益，无法进行提现，收益仅供参考',
            icon: 'none',
            duration: 5000
          })
          return
          self.setData({
            isWithdrawShow: true
          });
        } else {
          util.errHandler(res)
        }
      }
    });
  },

  confirmAction() {
    let self = this;

    let token = wx.getStorageSync("authorization");

    wx.showLoading({
      title: "加载中"
    });

    wx.request({
      url: api.cashApi,
      method: "POST",
      data: self.data.withdrawNum,
      header: {
        Authorization: "Bearer " + token
      },
      success(res) {
        wx.hideLoading();
        console.log(res);
        if (res.statusCode == "200") {
          let data = res.data;

          self.setData({
            isWithdrawConfirm: false
          });

          message.showSuccess("提现申请已提交")
        } else {
          util.errHandler(res)
        }
      }
    });
  }
});